<?php
/**
 * @ClassName: Shopgoodsapply
 * @Description: 产品申请
 * @author: gydtrade
 * @Date: 2024-09-09 22:08
 * @Version: V1.0.0
 */

namespace app\admin\controller;

use app\common\enum\CommonEnum;
use app\common\model;
use think\Controller;
use tpext\builder\traits\HasBuilder;

class Shopgoodsapply extends Controller
{
    use HasBuilder;

    protected $dataModel;
    protected $specValueModel;
    protected $specPriceModel;


    protected function initialize()
    {
        parent::initialize();

        $this->dataModel = new model\ShopGoods();
        $this->pageTitle = '产品申请';
        $this->enableField = 'status';
        $this->pagesize = 10;

        $this->specValueModel = new model\ShopGoodsSpecValue();
        $this->specPriceModel = new model\ShopGoodsSpecPrice();

        $this->indexWith = ['category', 'brand', 'store']; //列表页模型关联
    }

    /**
     * 构建搜索
     *
     * @return void
     */
    protected function buildSearch()
    {
        $search = $this->search;

        $search->text('name', '名称', 3)->maxlength(20);
        $search->select('category_id', '分类', 3)->dataUrl(url('/admin/shopcategory/selectPage'));
        $search->select('brand_id', '品牌', 3)->dataUrl(url('/admin/shopbrand/selectPage'));
        $search->select('store_id', '店铺', 3)->dataUrl(url('/admin/store.store/selectPage'));
        $search->select('shop_type', '商品类型', 3)->options(CommonEnum::StoreTypeText(true));
    }

    /**
     * 构建搜索条件
     * @return array
     */
    protected function filterWhere()
    {
        $searchData = request()->get();

        $where = [];
        $where[] = ['status', '<>', CommonEnum::check_success];//排除审核通过的（查询待审核、审核拒绝的）
        if (!empty($searchData['name'])) {
            $where[] = ['name', 'like', '%' . $searchData['name'] . '%'];
        }

        if (!empty($searchData['category_id'])) {
            $where[] = ['category_id', 'eq', $searchData['category_id']];
        }

        if (!empty($searchData['brand_id'])) {
            $where[] = ['brand_id', 'eq', $searchData['brand_id']];
        }

        if (!empty($searchData['store_id'])) {
            $where[] = ['store_id', 'eq', $searchData['store_id']];
        }

        if (!empty($searchData['shop_type'])) {
            $where[] = ['shop_type', 'eq', $searchData['shop_type']];
        }

        return $where;
    }

    /**
     * 构建表格
     *
     * @return void
     */
    protected function buildTable(&$data = [])
    {
        $table = $this->table;

        $table->show('id', 'ID');
        $table->show('admin_group', '商家');
        $table->match('store_id', '店铺')->to('{store_id}#{store.store_name}');
        $table->text('name', '名称');
        $table->image('logo', '封面图')->thumbSize(60, 60);
        $table->show('brand.name', '品牌');
        $table->show('category.name', '分类');
        $table->fields('prices', '销售价/市场/成本价')->with(
            $table->show('sale_price', '销售价'),
            $table->show('market_price', '市场价'),
            $table->show('cost_price', '成本价')
        );
        $table->text('stock', '库存')->autoPost('', true)->mapClass(['1'], 'disabled', 'many_price')->getWrapper()->addStyle('width:80px');

        $table->fields('times', '添加/修改时间')->with(
            $table->show('create_time', '添加时间'),
            $table->show('update_time', '修改时间')
        )->getWrapper()->addStyle('width:160px');

        $table->sortable('id, create_time');

        $table->getToolbar()
            ->btnAdd('', '添加', 'btn-primary', 'mdi-plus', 'data-layer-size="98%,98%"')
            ->btnEnableAndDisable('通过', '拒绝')
            ->btnDelete()
            ->btnRefresh();

        $table->getActionbar()
            ->btnEdit()
            ->btnDelete()
            ->btnView();
    }

    /**
     * 构建表单
     *
     * @param boolean $isEdit
     * @param array $data
     */
    protected function buildForm($isEdit, &$data = [])
    {
        $form = $this->form;

        $specList = $isEdit ? model\ShopGoodsSpec::where(['goods_id' => $data['id']])->order('sort')->select() : [];
        $attrList = $isEdit ? model\ShopGoodsAttr::where(['goods_id' => $data['id']])->order('sort')->select() : [];
        $priceList = $isEdit ? $this->specPriceModel->where(['goods_id' => $data['id']])->select() : [];

        $tab = input('tab', 0);

        $form->tab('基本信息');

        $form->defaultDisplayerSize(12, 12);

        $form->left(7)->with(
            $form->text('name', '名称')->required()->maxlength(55),
            $form->select('category_id', '分类')->required()->dataUrl(url('/admin/shopcategory/selectPage')),
            $form->select('brand_id', '品牌')->dataUrl(url('/admin/shopbrand/selectPage')),
//            $form->select('admin_group_id', '商家')->dataUrl(url('/admin/group/selectPage')),
            $form->select('store_id', '店铺')->dataUrl(url('/admin/store.store/selectPage')),
            $form->text('spu', 'spu码')->maxlength(100),
            $form->multipleSelect('tags', '标签')->dataUrl(url('/admin/shoptag/selectPage'))->help('可到【标签管理】菜单添加标签'),
            $form->tags('keyword', '关键字'),
            $form->textarea('description', '摘要')->maxlength(255),
            $form->wangEditor('content', '产品详情')->required()
        );

        $hasManyPrice = $isEdit && count($priceList) > 0 ? true : false;
        $form->right(5)->with(
            function ($f) use ($form, $isEdit, $hasManyPrice) { //匿名方法中使用了外部变量，要使用 use($vars...)
                $form->image('logo', '封面图')->required()->mediumSize();
                $form->text('share_commission', '分销佣金')->default(0);

                $form->text('sale_price', '销售价', 4)->required()->readonly($hasManyPrice)->help($hasManyPrice ? '存在多个规格型号，显示价为所有规格型号最低价' : '');
                $form->text('market_price', '市场价', 4);
                $form->text('cost_price', '成本价', 4);
                $form->html('');
                $form->number('stock', '库存', 4)->default(99)->readonly($hasManyPrice)->help($hasManyPrice ? '存在多个规格型号，总库存为所有规格型号总和' : '');
                $form->number('click', '点击量', 4)->default(1);
                $form->number('sales_sum', '销量', 4)->default(0);
                $form->html('');
                $form->radio('on_sale', '上架', 6)->blockStyle()->options([1 => '已上架', 0 => '未上架'])->default(0)->help('下架后不显示也不可购买');
                $form->datetime('publish_time', '上架时间', 6)->required()->default(date('Y-m-d H:i:s'));
                $form->checkbox('attr', '属性')->blockStyle()->checkallBtn()->options(['is_recommend' => '推荐', 'is_hot' => '热门', 'is_top' => '置顶']);
                $form->switchBtn('is_show', '显示')->default(1)
                    ->help('仅对已上架产品生效，未上架无论如何都不显示<br>已上架产品隐藏后不在产品列表显示，但仍可购买(通过某些途径进入产品详情页)');
                $form->number('sort', '排序')->default(0);
                $form->number('weight', '重量')->default(1000)->help('单位:克');

                if ($isEdit) {
                    $form->show('create_time', '添加时间', 6);
                    $form->show('update_time', '修改时间', 6);
                }
            }
        );

        $form->tab('多图/视频');
        $form->fields('', '', 10)->size(0, 12)->showLabel(false);
        $form->multipleImage('images', '多图')->mediumSize();
        $form->file('video', '视频')->video()->mediumSize()->jsOptions(['fileSingleSizeLimit' => 50 * 1024 * 1024]);
        $form->fieldsEnd();

        $form->tab('规格型号/属性', $tab == 3);

        $form->items('spec_list', '规格型号')->dataWithId($specList)->with(
            $form->text('name', '名称')->placeholder('规格名称，如颜色')->maxlength(55)->required()->getWrapper()->addStyle('width:200px;'),
            $form->text('sort', '排序')->placeholder('规格名称，如颜色')->default(1)->required()->getWrapper()->addStyle('width:80px;'),
            $form->tags('value', '可选值')->required()->getWrapper()->addStyle('min-width:70%;')
        )->help('【规格型号】会影响价格，根据排列组合，用户选择不同价格会不同。多个值用英文`,`号或回车键<i class="mdi mdi-subdirectory-arrow-left"></i>分割');

        $form->items('attr_list', '产品属性')->dataWithId($attrList)->with(
            $form->text('name', '名称')->placeholder('属性名称，如生产日期')->maxlength(55)->required()->getWrapper()->addStyle('width:200px;'),
            $form->text('sort', '排序')->placeholder('规格名称，如颜色')->default(1)->required()->getWrapper()->addStyle('width:80px;'),
            $form->text('value', '属性值')->required()->getWrapper()->addStyle('min-width:70%;')
        )->help('【属性】不影响价格，仅展示');

        if ($isEdit && count($specList)) {
            $form->tab('库存/价格设置', $tab == 4);
            $form->items('price_list', '设置')->help('规格型号增加/删除/修改后，先保存一次此处才显示最新规格');
            foreach ($specList as $spec) {
                foreach ($priceList as &$price) {
                    if ($price['data']) {
                        $savedData = json_decode($price['data'], 1);
                        if ($savedData && isset($savedData[$spec['id']])) {
                            $price['spec_id' . $spec['id']] = $savedData[$spec['id']];
                        }
                    }
                    //$price['img'] = '/uploads/images/202105/13/file1cee5058023a5f1f1d5e1d40c79efd5e5219.png';
                }

                $valueList = $this->specValueModel->where(['spec_id' => $spec['id']])->select();
                $form->select('spec_id' . $spec['id'], $spec['name'])->optionsData($valueList, 'value')->required();
            }

            $data['price_list'] = $priceList;

            $form->text('sku', 'SKU编码');
            $form->text('sale_price', '销售价格')->required();
            $form->number('stock', '库存')->required();
            $form->image('img', '封面图')->required()->thumbSize(40, 40);

            $form->itemsEnd();
        }
    }

    /**
     * 审核
     * @param $state
     * @return \think\response\Json
     */
    public function enable($state)
    {
        $ids = input('post.ids', '');
        $ids = array_filter(explode(',', $ids), 'strlen');

        if (empty($ids)) {
            return json(['code' => 0, 'msg' => '参数有误']);
        }

        if ($state) {
            $remark = '平台审核通过';
            $status = 1;
        } else {
            $remark = '平台审核不通过';
            $status = 2;
        }
        $res = 0;
        foreach ($ids as $id) {
            if ($this->trans($id, $remark, $status)) {
                $res += 1;
            }
        }
        if ($res) {
            return json(['code' => 1, 'msg' => '成功操作' . $res . '条数据']);
        } else {
            trace('审核操作失败');
            return json(['code' => 0, 'msg' => '审核操作失败']);
        }
    }

    /**
     * 审核操作
     * @param $id
     * @param $remark
     * @param $state
     * @return model\ShopGoods|\think\response\Json
     */
    private function trans($id, $remark, $state = 1)
    {
        $records = model\ShopGoods::where('id', $id)->find();

        if (!$records) {
            return json(['code' => 0, 'msg' => '商品不存在']);
        }
        if ($records['status'] != 0) {
            return json(['code' => 0, 'msg' => '商品状态不是待审核状态']);
        }

        $up_data = [
            'status' => $state,
            'audit_opinion' => $remark,
            'update_time' => date_now(),
        ];
        if ($state == 1) {
            $up_data['audit_time'] = date_now();
        }
        $res = true;
        $res = model\ShopGoods::where('id', $id)->update($up_data);

        return $res;
    }

    /**
     * 保存数据
     *
     * @param integer $id
     * @return void
     */
    private function save($id = 0)
    {
        $data = request()->only([], 'post');

        $result = $this->validate($data, []);

        if (!$result) {
            $this->error($result);
        }

        if ($id) {
            // 编辑
            $data['update_time'] = date_now();
        } else {
            // 新增
            $data['create_time'] = date_now();
            $data['update_time'] = date_now();
        }

        return $this->doSave($data, $id);
    }

}